function showTopButton(type) {
    if (type === "sender") {
        document.getElementById("selectBlock").style.display = "none";
        document.getElementById("selectGroup").style.display = "none";
        document.getElementById("selectType").style.display = "none";
    } else if (type === "admin") {
        document.getElementById("liveGroup").style.display = "none";
        document.getElementById("selectBlock").style.display = "none";
        document.getElementById("adminTypeOption").remove();
        document.getElementById("blockTypeOption").remove();
    } else { // type == root
        document.getElementById("liveGroup").style.display = "none";
        document.getElementById("liveBlock").style.display = "none";
    }
}

window.onpageshow = function () {

    let xmlhttp;
    if (window.XMLHttpRequest) {
        //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp = new XMLHttpRequest();
    } else {
        // IE6, IE5 浏览器执行代码
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
            let info = JSON.parse(xmlhttp.responseText);

            //  info[0] => name: , type: , user:
            //  info[1]: sender {block, group} , admin {block, groups:[]} , root {blocks:[]}

            let typeName = {"root": "超管员", "sender": "配送员", "admin": "管理员"};
            let type = info[0]["type"];

            document.getElementById("name").innerText = info[0]["name"] !== "null" ? info[0]["name"] : "无名";
            document.getElementById("type").innerText = typeName[type];
            document.getElementById("phone").innerText = "" + info[0]["user"];

            showTopButton(type);

            if (type === "sender") {
                document.getElementById("liveBlock").firstElementChild.innerHTML = info[1]["block"];
                document.getElementById("liveGroup").firstElementChild.innerHTML = info[1]["group"] + "";
            } else if (type === "admin") {
                document.getElementById("liveBlock").firstElementChild.innerHTML = info[1]["block"];
                let str = "";
                for (let group of info[1]["groups"]) {
                    str += "<option value=\"" + group + "\">" + group + "</option>";
                }
                document.getElementById("selectGroupOption").outerHTML = str;
            } else if (type === "root") {
                let str = "";
                for (let block of info[1]["blocks"]) {
                    str += "<option value=\"" + block + "\">" + block + "</option>";
                }
                document.getElementById("selectBlockOption").outerHTML = str;
            }


        }
    }
    xmlhttp.open("GET", "change", true);
    xmlhttp.send();
}


function showTime() {
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = month < 10 ? "0" + month : month;
    let day = date.getDate();
    day = day < 10 ? "0" + day : day;
    const week = date.getDay();

    let week_let = ["日", "一", "二", "三", "四", "五", "六"];

    let hour = date.getHours();
    hour = hour < 10 ? "0" + hour : hour;
    let minute = date.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    document.getElementById("time").innerHTML = year + "年" + month + "月" + day + "日 星期" + week_let[week] + " " + hour + ":" + minute;
}

showTime();
window.setInterval(function () {
    showTime()
}, 1000 * 30);

function dataCheck() {

    let block = getSelected("selectBlock");
    let group = getSelected("selectGroup");
    let type = getSelected("selectType");
    let keyword = document.getElementById("searchKeyword").value;
    let page = 1;

    let xmlhttp;
    if (window.XMLHttpRequest) {
        //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp = new XMLHttpRequest();
    } else {
        // IE6, IE5 浏览器执行代码
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
            /*
            *   responseText: [{type: selectedType}, {}, {}, {}, ...]
            * takeout: name phone block group time sender_phone status detail
            *  sender: name phone block group
            *   admin: name phone block
            * */
            let data = JSON.parse(xmlhttp.responseText);
            // console.log(xmlhttp.responseText);

            let type = data[0]["type"];
            let str;
            if (type === "takeout") {
                str = "<tr>" +
                    "<th>收货人</th>" +
                    "<th>收货号码</th>" +
                    "<th>区域</th>" +
                    "<th>组别</th>" +
                    "<th>配送时间</th>" +
                    "<th>配送员号码</th>" +
                    "<th>配送状态</th>" +
                    "<th>备注</th>";
            } else if (type === "sender") {
                str = "<tr>" +
                    "<th>配送员</th>" +
                    "<th>手机号码</th>" +
                    "<th>区域</th>" +
                    "<th>组别</th>";
            } else if (type === "admin") {
                str = "<tr>" +
                    "<th>管理员</th>" +
                    "<th>手机号码</th>" +
                    "<th>区域</th>";
            } else if (type === "group") {
                str = "<tr>" +
                    "<th>名称</th>" +
                    "<th>区域</th>" +
                    "<th>详细</th>";
            } else if (type === "block") {
                str = "<tr>" +
                    "<th>名称</th>" +
                    "<th>详细</th>";
            }

            str += "<th>选择</th></tr>"

            if (data.length > 1) {
                for (let i = 1; i < data.length; i++) {
                    str += "<tr>";
                    for (let k of Object.keys(data[i])) {
                        if (k !== "id")
                            str += "<td>" + data[i][k] + "</td>";
                        else
                            str += "<td style='display: none'>" + data[i][k] + "</td>";
                    }
                    str += "<td><input type='checkbox' name='checkBoxInPage'/></td></tr>";
                }

            }

            for (const child of document.getElementById("showData").firstElementChild.getElementsByTagName("tr")) {
                child.remove();
            }
            document.getElementById("showData").firstElementChild.innerHTML = str;


        }
    }
    xmlhttp.open("POST", "page", true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send("selectedBlock=" + block + "&selectedGroup=" + group + "&selectedType=" + type + "&keyword=" + keyword + "&page=" + page);
}

function getCheckBoxInfo(type) {
    let str = "";
    for (const box of document.getElementsByName("checkBoxInPage")) {
        if (box.checked) {
            let goal;
            if (type === "takeout" || type === "group" || type === "block") {
                goal = box.parentElement.parentElement.firstElementChild;
            } else if (type === "sender" || type === "admin") {
                goal = box.parentElement.parentElement.children[1];
            }

            str += ":" + goal.innerText;
        }
    }
    return str;
}

function batchDo(opera) {

    if(!confirm("是否" + (opera === "send" ? "送达" : "删除")))
        return;

    let selectedType = getSelected("selectType");
    let sl = getCheckBoxInfo(selectedType);

    if (sl.split(":").length < 1 || sl === "") {
        alert("没有选择");
        return;
    }

    let xmlhttp;
    if (window.XMLHttpRequest) {
        //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp = new XMLHttpRequest();
    } else {
        // IE6, IE5 浏览器执行代码
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
            // responseText [{state: }, {fail:[]}]
            //  state: 0 - error  1 - success   2 - partial success
            let data = JSON.parse(xmlhttp.responseText);
            let returnState = parseInt(data[0]["state"]);


            if (returnState === 1) {
                // openMyWindow("全部操作成功！", "");

                alert("全部操作成功！");
                dataCheck();
            } else if (returnState === 2) {
                //  失败在 data[1]["fail"]

                // let msg = "<p>以下操作失败：</p>";
                //
                // for(let f of data[1]["fail"])
                //     msg += "<p>" + f + "</p>";
                //
                // openMyWindow("部分操作成功！", msg);

                alert("部分操作成功！");
                dataCheck();
            } else {
                // openMyWindow("未知错误", "错误码：" + returnState);
                alert("未知错误: " + returnState);
            }

        }
    }

    sl += ":" + selectedType;

    xmlhttp.open("POST", opera, true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(sl);
}

// function openMyWindow(title, msg) {
//     let modal = document.getElementById('myModal');
//     modal.firstElementChild.getElementsByTagName("h4")[0].innerText = title;
//     modal.firstElementChild.getElementsByTagName("div")[0].innerHTML = msg;
//     modal.style.display = "block";
// }
//
// window.onclick = function(event) {
//     let modal = document.getElementById('myModal');
//     if (event.target === modal) {
//         modal.style.display = "none";
//     }
// }
//
// document.querySelector(".close").onclick = function () {
//     document.getElementById('myModal').style.display = "none";
// }
